package cn.com.bluemoon.daps.sync.core.sync.compare.sql;

import cn.com.bluemoon.daps.model.entity.DapDataModelTable;
import cn.com.bluemoon.daps.sync.base.BmScript;
import cn.com.bluemoon.daps.sync.base.ModifyType;
import cn.com.bluemoon.daps.sync.base.SqlCompareResult;
import cn.com.bluemoon.daps.sync.core.sync.GlobalConfig;
import cn.com.bluemoon.daps.sync.core.sync.Tuple2;
import cn.com.bluemoon.daps.sync.core.sync.compare.IndexComparator;
import lombok.extern.slf4j.Slf4j;

import java.util.List;

/**
 * @author Jarod.Kong
 * @date 2021/6/3 13:39
 */
@Slf4j
public class SqlIndexComparator extends IndexComparator<SqlCompareResult> {
    public SqlIndexComparator(GlobalConfig globalConfig, Tuple2<DapDataModelTable> tableTuple2) {
        super(globalConfig, tableTuple2);
    }

    @Override
    public void change0(List<SqlCompareResult> sqlCollector) {
        super.change0(sqlCollector);
        BmScript sql = bmSql.changeIndex(newTable, getOldT(), getNewT());
        sqlCollector.add(SqlCompareResult.builder()
                .modifyType(ModifyType.ALTER.index())
                .script(sql)
                .build());
    }

    @Override
    public void drop0(List<SqlCompareResult> sqlCollector) {
        // 针对模型没有而数据库有的表，目前需求是忽略数据库的表，而不进行删除表+字段+索引
        if (!globalConfig.isCanDropDbTable() && oldTable != null && newTable == null) {
            log.debug("开发同步中：针对模型没有而数据库有的表，目前需求是忽略数据库的表，而不进行删除表索引, table:{}", oldTable);
        } else if (oldTable != null && newTable != null) {// 要是删除表，字段就忽略删除，否则会找不到表；要是修改字段，则进行生产语句
            super.drop0(sqlCollector);
            BmScript sql = bmSql.dropIndex(oldTable, getOldT());
            sqlCollector.add(SqlCompareResult.builder()
                    .modifyType(ModifyType.DROP.index())
                    .script(sql)
                    .build());
        }
    }

    @Override
    public void create0(List<SqlCompareResult> sqlCollector) {
        if (oldTable == null && newTable != null) {
            log.debug("新建表，忽略创建表的创建索引sql，统一有SqlTableComparator#create0生产, table:{}", newTable);
            return;
        }
        super.create0(sqlCollector);
        BmScript sql = bmSql.createIndex(newTable, getNewT());
        assert newTable != null;
        sqlCollector.add(SqlCompareResult.builder()
                .modifyType(ModifyType.CREATE.index())
                .script(sql)
                .build());
    }
}
